package com.cmcc.driver.ui.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.DriverDataRepository
import com.cmcc.driver.data.entity.OrderTemp
import com.cmcc.driver.databinding.DialogOrderGrabBinding
import com.cmcc.driver.ui.main.DriverMainActivity
import com.cmcc.driver.ui.main.viewmodel.OrderReceiveViewModel
import com.cmcc.driver.util.LocationUtil
import com.cmcc.shared.utils.SpHelper
import com.cmcc.shared.utils.clickWithTrigger
import java.lang.String.format
import java.util.*
import kotlin.math.*

/**
 * Author: jiangxin
 * Date: 2019/11/6
 * Description:
 */
class OrderGrabDialog private constructor() : DialogFragment() {

    private lateinit var binding: DialogOrderGrabBinding
    private var timer: Timer? = null

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val inflater = LayoutInflater.from(context)
        binding = DataBindingUtil.inflate(inflater, R.layout.dialog_order_grab, null, false)
        val dialog = Dialog(context!!, R.style.AppDialogStyle)
        dialog.setContentView(binding.root)

        val m = activity!!.windowManager
        val d = m.defaultDisplay
        val p = dialog.window!!.attributes
        p.width = (d.width * 0.9).toInt()
        dialog.window!!.attributes = p
        val viewModel = ViewModelProviders.of(this).get(OrderReceiveViewModel::class.java)
        val order = arguments?.getParcelable<OrderTemp>("order")

        coverToDistance(order)

        binding.orderType.text = if(order?.type == 1) getString(R.string.real_time_Grab) else getString(R.string.reservation_grab)
        binding.orderType.setmDegrees(-45)

        var type = SpHelper.getParam(context, "Mode", "type", "1")

        //当前是夜间模式 设置成白天模式
        if (type == "1") {
            binding.orderType.setTextColor(ContextCompat.getColor(context!!, R.color.driver_lean_color))
        }else {
            binding.orderType.setTextColor(ContextCompat.getColor(context!!, R.color.driver_lean_color_white))
        }

        binding.direction.directionStart.text = order?.startAddress
        binding.direction.directionEnd.text = order?.endAddress
        binding.tunnel.text =
            getString(R.string.order_tunnel, order?.tunnelName ?: getString(R.string.what_ever))
        binding.remarks.text = getString(
            R.string.order_remark,
            if (order?.remark.isNullOrEmpty()) getString(R.string.none) else order?.remark
        )
        binding.tip.text = getString(R.string.order_tip) + (order?.bountyFee ?: "0.00")
        binding.station.text = getString(
            R.string.order_station,
            if (order?.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") getString(R.string.what_ever) else order?.stationIndex
        )
        binding.grabOrder.clickWithTrigger {
            if (order?.id != null)
                viewModel.receivingOrder(order.id)
        }

        viewModel.orderReceiving.observe(this, Observer { orderReceiving ->
            val code = orderReceiving.code
            when(code) {
                200 ->{
//                if (activity is DriverMainActivity)
//                    (activity as DriverMainActivity).currentPage(
//                        R.id.order_progress
//                    )
                    ARouter.getInstance().build(DriverPath.ORDER_IN_PROGRESS_DETAIL)
                        .withString("orderId", orderReceiving.data).navigation()
                    DriverDataRepository.getInstance().hasStatusChange().value = true
                }
                1001 ->{
                    Toast.makeText(
                        context!!,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                }
                1003 ->{
                    Toast.makeText(
                        context!!,
                        orderReceiving.msg,
                        Toast.LENGTH_LONG
                    ).show()
                }
                400 ->{
                    Toast.makeText(
                        context!!,
                        getString(R.string.operate_failed_retry),
                        Toast.LENGTH_LONG
                    ).show()
                }
                else ->{
                    Toast.makeText(
                        context,
                        getString(R.string.driver_has_doing_order),
                        Toast.LENGTH_SHORT
                    ).show()
                    if (activity is DriverMainActivity)
                        (activity as DriverMainActivity).currentPage(
                            R.id.order_progress
                        )
                }
            }
            onDismiss()
        })
        startTimer()
        return dialog
    }

    companion object {
        fun newFragment(order: OrderTemp): OrderGrabDialog {
            val dialog = OrderGrabDialog()
            val bundle = Bundle()
            bundle.putParcelable("order", order)
            dialog.arguments = bundle
            return dialog
        }
    }

    private fun startTimer() {
        timer = Timer()
        val task = object : TimerTask() {
            override fun run() {
                onDismiss()
            }
        }
        timer?.schedule(task, 5 * 1000L)
    }

    private fun onDismiss() {
        timer?.cancel()
        timer = null
        dismiss()
    }

    private fun coverToDistance(order: OrderTemp?) {
        val endLat = order?.startCoordinates?.y ?: 0.0
        val endLng = order?.startCoordinates?.x ?: 0.0


        val latLng = LocationUtil.getInstance().getCurrentLoc()
        val lastLat = latLng?.latitude ?: 0.0
        val lastLng = latLng?.longitude ?: 0.0


        val r = 6378137
        val dLat = (endLat - lastLat) * Math.PI / 180
        val dLng = (endLng - lastLng) * Math.PI / 180

        val a =
            sin(dLat / 2) * sin(dLat / 2) + cos(lastLat * Math.PI / 180) * cos(endLat * Math.PI / 180) * sin(
                dLng / 2
            ) * sin(dLng / 2)
        val c = 2 * atan2(sqrt(a), sqrt(1 - a))
        val d = r * c

        binding.distance.text = getString(R.string.distance, format("%.1f", d / 1000))


    }
}